#include "mainwindow.h"
#include <opencv2/opencv.hpp>
#include <QPushButton>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_btn(new QPushButton("生成"))
    , m_mainWdg(new QWidget(this))
    , m_edtSelect(new QLineEdit())
    , m_btnSelect(new QPushButton("选择视频路径"))
    , m_layoutSelect(new QHBoxLayout())
    , m_edtSave(new QLineEdit())
    , m_btnSave(new QPushButton("图片保存路径"))
    , m_layoutSave(new QHBoxLayout())
    , m_layoutMain(new QVBoxLayout())

{
    initUI();
    initConnect();
}

MainWindow::~MainWindow()
{

}

void MainWindow::slotClickBtn()
{   // 打开视频文件
    QString strFileName = m_edtSelect->text();
    if(strFileName.isEmpty()){
        QMessageBox::information(this,"提示","为选择视频文件");
        return;
    }
    cv::VideoCapture video(strFileName.toStdString().c_str());

    // 检查视频是否成功打开
    if (!video.isOpened()) {
        std::cerr << "无法打开视频文件" << std::endl;

    }

    // 读取视频的帧率和总帧数
    double fps = video.get(cv::CAP_PROP_FPS);
    int totalFrames = video.get(cv::CAP_PROP_FRAME_COUNT);
    QString FilePath = m_edtSave->text();
    // 逐帧读取视频并保存为图像文件
    for (int frameNumber = 0; frameNumber < totalFrames; ++frameNumber) {
        cv::Mat frame;
        video.read(frame);

        // 检查是否成功读取帧
        if (frame.empty()) {
            std::cerr << "无法读取视频帧" << std::endl;
            break;
        }

        // 生成图像文件名，例如 frame_0001.jpg
        std::string filename = FilePath.toStdString() + "/frame_" + std::to_string(frameNumber + 1) + ".jpg";

        // 保存帧为图像文件
        cv::imwrite(filename, frame);
    }

    // 关闭视频文件
    video.release();
    QMessageBox::information(this,"提示","生成完成");
    std::cout << "视频分解完成，共生成 " << totalFrames << " 张图像文件。" << std::endl;

}

void MainWindow::slotSelectVideo()
{
   QString strFileName = QFileDialog::getOpenFileName();
   m_edtSelect->setText(strFileName);
}

void MainWindow::slotSaveImg()
{
    QString strPath = QFileDialog::getExistingDirectory();
    m_edtSave->setText(strPath);
}

void MainWindow::initUI()
{
    setMinimumWidth(500);
    m_edtSelect->setDisabled(true);
    m_layoutSelect->addWidget(m_edtSelect);
    m_layoutSelect->addWidget(m_btnSelect);

    m_layoutSave->addWidget(m_edtSave);
    m_layoutSave->addWidget(m_btnSave);

    m_layoutMain->addLayout(m_layoutSelect);
    m_layoutMain->addLayout(m_layoutSave);
    m_layoutMain->addWidget(m_btn);
    m_mainWdg->setLayout(m_layoutMain);
    setCentralWidget(m_mainWdg);
}

void MainWindow::initConnect()
{
    connect(m_btn,&QPushButton::clicked,this,&MainWindow::slotClickBtn);
    connect(m_btnSelect,&QPushButton::clicked,this,&MainWindow::slotSelectVideo);
    connect(m_btnSave,&QPushButton::clicked,this,&MainWindow::slotSaveImg);
}
